package com.sangmo.boot.auth.core.model;

import com.sangmo.boot.framework.data.entity.general.AuditEntity;
import com.sangmo.boot.framework.data.entity.guid.GuidAuditEntity;

import javax.persistence.Entity;
import javax.persistence.Table;
import java.beans.Transient;
import java.util.Date;

@Entity
@Table(name = "authorize_code")
public class AuthorizeCode extends AuditEntity {
	public static final int MAX_FAILURE = 3;
	private String clientId;
	private String code;
	private Date usedTime;
	private String randomStr;
	private int failure;
	private int validity;
	private Date refreshTime;
	private String username;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public Date getUsedTime() {
		return usedTime;
	}

	public void setUsedTime(Date usedTime) {
		this.usedTime = usedTime;
	}

	public String getRandomStr() {
		return randomStr;
	}

	public void setRandomStr(String randomStr) {
		this.randomStr = randomStr;
	}

	public int getFailure() {
		return failure;
	}

	public void setFailure(int failure) {
		this.failure = failure;
	}

	public String getClientId() {
		return clientId;
	}

	public void setClientId(String clientId) {
		this.clientId = clientId;
	}

	public int getValidity() {
		return validity;
	}

	public void setValidity(int validity) {
		this.validity = validity;
	}

	public Date getRefreshTime() {
		return refreshTime;
	}

	public void setRefreshTime(Date refreshTime) {
		this.refreshTime = refreshTime;
	}

	@Transient
	public long getLeftValidity() {
		long now = System.currentTimeMillis();
		long time = refreshTime.getTime() + (validity * 1000);
		long left = (time - now) / 1000;
		return left > 0 ? left : 0;
	}

	@Transient
	public boolean isExpired() {
		if (null != usedTime) {
			return true;
		}
		long now = System.currentTimeMillis();
		if (this.failure >= MAX_FAILURE) {
			return false;
		}
		if(-1 == this.validity) {
			return false;
		}
		long time = refreshTime.getTime() + (validity * 1000);
		return now >= time;
	}
}
